/*
 * @lc app=leetcode.cn id=234 lang=javascript
 *
 * [234] 回文链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
  if (!head) {
    return true;
  }

  // 一半
  const getHalf = (head) => {
    let slow = head;
    let fast = head;
    while (fast.next && fast.next.next) {
      slow = slow.next;
      fast = fast.next.next;
    }
    return slow;
  };
  // 翻转
  const reverseList = (head) => {
    let pre = null;
    let p = head;
    while (p) {
      const next = p.next;
      p.next = pre;
      pre = p;
      p = next;
    }
    return pre;
  };

  const halfEnd = getHalf(head);
  const halfStart = reverseList(halfEnd.next);

  let p1 = head;
  let p2 = halfStart;
  let result = true;
  while (result && p2) {
    if (p1.val !== p2.val) {
      result = false;
    }
    p1 = p1.next;
    p2 = p2.next;
  }

  halfEnd.next = reverseList(halfStart);

  return result;
};
// @lc code=end
